/*!
 @header CirclePickerViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/30 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

//  -业务逻辑细节说明-
//
//  @abstract       本类用于构建一个圈子的拾取器。可以显示所有的圈子，并且可以设定那些圈子默认被选择了。通过代理方法，返回当前视图，那些圈子是被选择的。
//                  点击“邀请”按钮，会push到邀请方式VC。

//  @discussion

//  @notes

//  -类修改日志-
//  修改人   修改时间     针对版本                   修改描述


#import "CirclePickerViewController.h"
#import "DBKit.h"
#import "Helper.h"
#import "Config.h"
#import "JMFBase.h"

@interface CirclePickerViewController ()

@end

@implementation CirclePickerViewController

@synthesize delegate = _delegate;
@synthesize pickedCircles = _pickedCircles;
@synthesize indicators = _indicators;
@synthesize dataSource = _dataSource;
//静态实例
static CirclePickerViewController* sharedCirclePickerViewController = nil;

/*!
 @abstract 返回一个静态的CirclePickerViewController实例
 */
//+ (CirclePickerViewController *)sharedCirclePickerViewController
//{
//    @synchronized(self) {
//        if (!sharedCirclePickerViewController) {
//            sharedCirclePickerViewController = [[self alloc] initWithStyle:UITableViewStyleGrouped];
//        }
//    }
//    return sharedCirclePickerViewController;
//}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //标题
    self.title = _L(@"vc_title_031");
    
    [self.tableView setBackgroundView:nil];
    
    [self.view setBackgroundColor:_SYS_COLOR_BACKGROUND];
    
    //导航按钮左侧：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //导航按钮右侧：确定
    UIButton* saveButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    [saveButton addTarget:self action:@selector(saveButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_LIST];
    request.delegate = (id)self;
    [request setHUD:HUDStyleModeTitle withView:self.view];
    request.hudTitle = _L(@"title_loading_01");
    [request asynchronous];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//  视图退出后清空数据，回收资源，因为有可能实例是静态对象
//
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    //_indicators必须回收，移除所有元素后，置为nil。如果不置为nil，只清空，那么会在下一次静态实例打开时，读数组时objectAtIndex:方法异常
//    [_indicators removeAllObjects];
//    _indicators = nil;
//    _pickedCircles = nil;
//
//    [self.tableView reloadData];
}

- (void)dealloc
{
    _indicators = nil;
    _pickedCircles = nil;
    _dataSource = nil;
}

// 视图将要载入时，刷新圈子信息
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_LIST];
//    request.delegate = (id)self;
//    [request setHUD:HUDStyleModeTitle withView:self.view];
//    request.hudTitle = _L(@"title_loading_01");
//    [request asynchronous];
//}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 240, 25)];
        nameLabel.font = _SYS_FONT_003;
        nameLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:nameLabel];
        
        UIImageView* selectorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(270, 15, 14, 14)];
        selectorImageView.backgroundColor = [UIColor redColor];
        [cell.contentView addSubview:selectorImageView];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    NSDictionary* circle = [_dataSource objectAtIndex:indexPath.row];
    NSNumber* selector = [_indicators objectAtIndex:indexPath.row];
    ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = [circle objectForKey:@"name"];
    ((UIImageView*)[cell.contentView.subviews objectAtIndex:1]).image = [selector boolValue] ? [UIImage imageNamed:@"com_icon_011"] : [UIImage imageNamed:@"com_icon_010"];
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    //把当前行对应的_selector值取出来后，取bool值，然后做非运算，在用新的对象替换
    NSNumber* indicator = [_indicators objectAtIndex:indexPath.row];
    //一定要用replace，因为_select是NSMutableArray
    [_indicators replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool: ! indicator.boolValue]];
    
    //获取当前被点中的行的Cell，按_selector的值的状态，切换图片
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    ((UIImageView*)[cell.contentView.subviews objectAtIndex:1]).image = [[_indicators objectAtIndex:indexPath.row] boolValue] ? [UIImage imageNamed:@"com_icon_011"] : [UIImage imageNamed:@"com_icon_010"];
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    [self.navigationController dismissModalViewControllerAnimated:true];
}

/*!
 @abstract 确定按钮事件。将被选中的圈子对象，通过代理方法，发送给调用者
 */
- (void)saveButtonEvent
{
    NSMutableArray* circles = [[NSMutableArray alloc] init];
    
    //遍历_selector，如果某一个元素值为true，就将_dataSource中对应的Circle对象存入返回数组
    for (int i = 0; i < _indicators.count; i++) {
        if ([[_indicators objectAtIndex:i] boolValue]) {
            [circles addObject:[_dataSource objectAtIndex:i]];
        }
    }
    
    //调用代理方法，选中的圈子值发送出去
    [_delegate circlesPicked:circles];
    [self.navigationController dismissModalViewControllerAnimated:true];
}

- (NSMutableArray *)circlesWeGot
{
    NSMutableArray* circles = [[NSMutableArray alloc] init];
    
    //遍历_selector，如果某一个元素值为true，就将_dataSource中对应的Circle对象存入返回数组
    for (int i = 0; i < _indicators.count; i++) {
        if ([[_indicators objectAtIndex:i] boolValue]) {
            [circles addObject:[_dataSource objectAtIndex:i]];
        }
    }
    
    return circles;
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        //成功的获取了圈子数据后，清除_dataSource的数据。后面会对这个部分重新填充
        //判断一下是否有实例
        if (_dataSource == nil) {
            _dataSource = [[NSMutableArray alloc] init];
        }
        [_dataSource removeAllObjects];
        
        if (_indicators == nil) {
            _indicators = [[NSMutableArray alloc] init];
        }
        

        //取出圈子列表
        [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
        
        for (int i = 0; i < _dataSource.count; i++) {

            //根据外部传入值，做选中指示器_indicators的初始化
            BOOL selected = false;
            for (NSDictionary* c in _pickedCircles) {
                
                if ([[c objectForKey:@"id"] integerValue] == [[[_dataSource objectAtIndex:i] objectForKey:@"id"] integerValue]) {
                    selected = true;
                    break;
                }
            }
            //指示器根据selected的结果值来添加元素。_dataSource每添加一个，_indicators就添加一个
            [_indicators addObject:[NSNumber numberWithBool:selected]];
        }
        
        [self.tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }

}


- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
